//
//  ViewController.m
//  Prova2
//
//  Created by Diego on 17/07/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "ViewController.h"
#import "CommonCrypto/CommonCryptor.h"
#import "NSData+AESCrypt.h"
#import "NSString+AESCrypt.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "NSData+Conversion.h"
#import "Define.h"
#import "ComunicationsUtils.h"
#import "SBJson.h"
#import "CryptoCR2.h"
#import "JsonCR2.h"
#import "EnterViewController.h"
#import "Utente.h"
#import "OptionViewController.h"
#import "CoreDataManager.h"
#import "ClienteCD.h"

@implementation ViewController

@synthesize username,password,popUp;

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [[NSUserDefaults standardUserDefaults] setObject:@"yes" forKey:AUTO_LOGIN];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (void)viewDidAppear:(BOOL)animated{
    if([ComunicationsUtils getUrl] == nil){
        UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"Benvenuto su Interventix"
                                                              message:@"Interventix è stata avviata per la prima volta. Inserire l'indirizzo per la connessione al server che è stato fornito nel contratto." delegate:self cancelButtonTitle:nil otherButtonTitles:@"Impostazioni", nil];
        [myAlertView show];
    }else{
        NSString *autoLogin = [[NSUserDefaults standardUserDefaults] objectForKey:AUTO_LOGIN];
        if(autoLogin != nil){
            if([autoLogin isEqualToString:@"yes"]){
                NSString *stringCR2 = (NSString *) [[NSUserDefaults standardUserDefaults] objectForKey:SAVE_USER];
                if(stringCR2 != nil){
                    @try {
                        NSString *dec = [CryptoCR2 decrypt:stringCR2];
                        Utente *u =[Utente createFromDictionary:[dec JSONValue]];
                        [self next:u];
                    }
                    @catch (NSException *exception) {
                        NSLog(@"%@",exception);
                    }
                    @finally {}
                }
            }else{
                NSLog(@"Autologin == no");
            }
        }else{
            NSLog(@"Autologin == nil");
        }
    }
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0){
        OptionViewController *opz = [self.storyboard instantiateViewControllerWithIdentifier:@"OptionViewController"];
        //[self.navigationController pushViewController:opz animated:TRUE];
        
        
        [UIView  beginAnimations:nil context:NULL];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        [UIView setAnimationDuration:0.75];
        [self.navigationController pushViewController:opz animated:NO];
        [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.navigationController.view cache:NO];
        [UIView commitAnimations];
    }
}

- (void)didPresentAlertView:(UIAlertView *)alertView{
    /*CoreDataManager *core = [[CoreDataManager alloc] init];
    UIProgressView *pv;
    for(int i=0; i<alertView.subviews.count; i++){
        if ([[alertView.subviews objectAtIndex:i] isKindOfClass:[UIProgressView class]]) {
            pv = [alertView.subviews objectAtIndex:i];
        }
    }
    [core addContattiMT:pv];
    [core showClienti];*/
}

-(IBAction)send{    
   /* UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Caricamento in corso" message:@"" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
    UIProgressView *pv = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleBar];
    pv.frame = CGRectMake(20, 60, 240, 15);
    pv.progress = 0.5;
    [av addSubview:pv];
    [av show];*/
    /*CoreDataManager *core = [[CoreDataManager alloc] init];
    ClienteCD *cliente = [core find:[NSNumber numberWithInt:33]];
    NSLog(@"%@ -- %@",cliente.idcliente, cliente.nominativo);
    */
    
    //[core addContattiMT:pv];
    //[core showClienti];
    
    
    
    
    // Richiesta di login
    NSString *req_login = [JsonCR2 createRequestLogin:self.username.text andPassword:self.password.text];
    ASIFormDataRequest * request = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:[ComunicationsUtils getUrl]]];
    [request setTimeOutSeconds:20];
    [request setDelegate:self];
    [request setPostValue:req_login forKey:@"DATA"];
    [request startAsynchronous];
    
    //PopUp
    self.popUp=[[UIAlertView alloc] initWithTitle:@"Attenzione!" message:nil delegate:self cancelButtonTitle:@"Chiudi" otherButtonTitles:nil];
    UIActivityIndicatorView *loading=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    loading.frame=CGRectMake(121.0f, 50.0f, 37.0f, 37.0f);
    [loading startAnimating];
    self.popUp = [[UIAlertView alloc] initWithTitle:@"Connessione..." message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
    [self.popUp addSubview:loading];
    [self.popUp show];
}



- (void)requestFinished:(ASIHTTPRequest *)request		
{
    [popUp dismissWithClickedButtonIndex:0 animated:TRUE];
    
    NSString *json_res = [request responseString];
    NSDictionary *json = [JsonCR2 read:json_res];
    NSString *response = [json objectForKey:@"response"];
    //NSString *code = [json objectForKey:@"code"];
    
    if([response isEqualToString:@"success"]){
        NSDictionary *user_json = [json objectForKey:@"data"];
        Utente *u = [Utente createFromDictionary:user_json];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:SAVE_USER];
        [[NSUserDefaults standardUserDefaults] setObject:(NSString *)[CryptoCR2 encrypt:[user_json JSONRepresentation]] forKey:SAVE_USER];
        [self next:u];
    }else{
         self.popUp=[[UIAlertView alloc] initWithTitle:@"Attenzione!" message:@"Errore di Login!!!" delegate:self cancelButtonTitle:@"Chiudi" otherButtonTitles:nil];
        [self.popUp show];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",[error description]);
    
    if(error.code == 2){
        NSLog(@"TIMEOUT");
        
        [popUp dismissWithClickedButtonIndex:0 animated:TRUE];
        
        self.popUp=[[UIAlertView alloc] initWithTitle:@"Attenzione!" message:@"Errore di Timeout!!!" delegate:self cancelButtonTitle:@"Chiudi" otherButtonTitles:nil];
        [self.popUp show];
    }
}

-(void)next: (Utente *) u {
    EnterViewController *view = [self.storyboard instantiateViewControllerWithIdentifier:@"EnterViewController"];
    view.user = u;
    view.login = TRUE;
    [self.navigationController pushViewController:view animated:TRUE];
}

-(IBAction)options{
    OptionViewController *opz = [self.storyboard instantiateViewControllerWithIdentifier:@"OptionViewController"];
    //[self.navigationController pushViewController:opz animated:TRUE];
    
    
    [UIView  beginAnimations:nil context:NULL];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.75];
    [self.navigationController pushViewController:opz animated:NO];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.navigationController.view cache:NO];
    [UIView commitAnimations];
}





@end
